package com.ww.springboot.rabbitmq.mq.init;

import com.ww.springboot.rabbitmq.mq.QueueConstants;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.DirectExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.stereotype.Component;

/**
 * 遍历所有的 枚举队列 手动注册队列等相关bean到spring容器中
 *
 * @author wanwei
 */
@Component
public class QueueRegisterAware implements BeanFactoryAware {


    /**
     * 动态创建队列 交换器 绑定器
     *
     * @param beanFactory spring对象工厂
     * @throws BeansException
     */
    @Override
    public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
        DefaultListableBeanFactory defaultListableBeanFactory = (DefaultListableBeanFactory) beanFactory;
        for (QueueConstants.QueueEnum value : QueueConstants.QueueEnum.values()) {
            // 正常消息 队列 交换器 路由键绑定
            Queue queue = new Queue(value.getQueueName());
            DirectExchange directExchange = new DirectExchange(value.getExchangeEnum().getExchangeName());
            Binding binding = BindingBuilder.bind(queue).to(directExchange).with(value.getRoutingKey());
            // 注册bean
            defaultListableBeanFactory.registerSingleton(value.getQueueName(), queue);
            defaultListableBeanFactory.registerSingleton(value.getExchangeEnum().getExchangeName(), directExchange);
            defaultListableBeanFactory.registerSingleton(value.getRoutingKey(), binding);
        }

//		// 重试队列 交换器 路由键
//		Map<String, Object> dlqParamMap = new HashMap<>(2);
//		dlqParamMap.put("x-dead-letter-exchange", QueueConstants.DEAD_LETTER_EX);
//		dlqParamMap.put("x-dead-letter-routing-key", QueueConstants.DEAD_LETTER_ROUTING_KEY);
//		Queue retryQueue = new Queue(QueueConstants.QUEUE_RETRY, true, false, false, dlqParamMap);
//		DirectExchange directExchange = new DirectExchange(QueueConstants.DEAD_LETTER_EX);
//		Binding retryBindIng = BindingBuilder.bind(retryQueue).to(directExchange).with(QueueConstants.DEAD_LETTER_ROUTING_KEY);
//		defaultListableBeanFactory.registerSingleton(QueueConstants.QUEUE_RETRY, retryQueue);
//		defaultListableBeanFactory.registerSingleton(QueueConstants.DEAD_LETTER_ROUTING_KEY, retryBindIng);

    }


}
